package com.hxzy.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.util.MarketThreadLocalUtil;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.service.TokenService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 拦截后台请求拦截器(springmvc)
 */
@Component
@Log4j2
public class AdminTokenInterceptor  implements HandlerInterceptor {

    @Qualifier(value = "adminTokenService")
    @Autowired
    private TokenService<AdminLoginResp>  tokenService;

    /**
     * 在执行Controller方法之前的验证 (前置增强)
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation     controller中的方法
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("拦截器，当前线程ID是:"+ Thread.currentThread().getId());
        //Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjU3ODZlYzY5LWZjYTMtNDJjOS1iNmRjLTZmOWJiODkyNWU5MSJ9.DfAhxyXioZ1sXfmBNwIYSPonw6gck0hSd4wkWSbRfQnyim4jS6AWX43WwPMHqLHKz7GPX3C9pM_IMm-GjIbK1
        String jwtStr=request.getHeader(MarketConstants.ADMIN_REQUEST_HEADER_KEY);
        if(StrUtil.isBlank(jwtStr)){
            //有可能在参数中携带的
            jwtStr=request.getParameter("token");
            if(StrUtil.isBlank(jwtStr)) {
                //没有令牌 ,这个提交必须与前端vue的 utils/request.js中的第44行对起来  if (res.code === 619 || res.code === 614 || res.code === 611)
                throw new ServiceException(AckCode.TOKEN_NOT_BLANK);
            }
        }

        //根据jwt从redis中获取数据
        AdminLoginResp loginResp = this.tokenService.getLoginResp(jwtStr);
        if(Objects.isNull(loginResp)){
            throw new ServiceException(AckCode.APPLE_ILLEGAL);
        }

        //使用本地线程池，把当前解析出来的AdminLoginResp存起来，供当前线程后面的方法调用

        MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.set(loginResp);

        return true;
    }

    /**
     * controller方法执行完成以后要做的事情(后置增强)
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link HandlerMethod}) that started asynchronous
     * execution, for type and/or instance examination
     * @param modelAndView the {@code ModelAndView} that the handler returned
     * (can also be {@code null})
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       //移出线程池中的数据
        MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.remove();

    }
}
